package hlhj.fhp.burst.fragment

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.liaoinstan.springview.container.DefaultFooter
import com.liaoinstan.springview.container.DefaultHeader
import com.liaoinstan.springview.widget.SpringView
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.lzy.okgo.request.base.Request
import com.tbruyelle.rxpermissions.RxPermissions
import com.tenma.ventures.bean.TMUser
import com.tenma.ventures.bean.utils.TMLocationUtils
import com.tenma.ventures.bean.utils.TMSharedPUtil
import com.tenma.ventures.config.TMServerConfig
import com.tenma.ventures.share.bean.TMLinkShare
import com.tenma.ventures.share.util.TMShareUtil
import ezy.ui.view.BannerView
import hlhj.fhp.burst.*
import hlhj.fhp.burst.activitys.*
import hlhj.fhp.burst.adapter.CommentAdp
import hlhj.fhp.burst.adapter.FullyGridLayoutManager
import hlhj.fhp.burst.adapter.NineGridAdp
import hlhj.fhp.burst.adapter.Vpadp
import hlhj.fhp.burst.bean.BaseBean
import hlhj.fhp.burst.bean.BurstListBean
import hlhj.fhp.burst.camera.util.LogUtil
import hlhj.fhp.burst.customView.EditPop
import hlhj.fhp.burst.customView.LoadingDialog
import hlhj.fhp.burst.ninegrid.ImageInfo
import hlhj.fhp.burst.ninegrid.preview.NineGridViewClickAdapter
import kotlinx.android.synthetic.main.burst_head_pager.view.*
import kotlinx.android.synthetic.main.home_fgm.*
import kotlinx.android.synthetic.main.home_fgm.view.*
import kotlin.collections.ArrayList

/**
 * Created by Administrator on 2018\6\1 0001.
 */
class BurstFgm :Fragment(), SpringView.OnFreshListener {

    companion object {
        var isFromImage=false
    }
    private lateinit var rooView:View
    private var page=1;
    private lateinit var loadDialog: LoadingDialog
    private lateinit var pagerAdp: Vpadp
    private val pagerDatas= ArrayList<BurstListBean.DataBean.BannerBean>()
    private lateinit var adp : BaseQuickAdapter<BurstListBean.DataBean.ListBean, BaseViewHolder>
    private val datas= ArrayList<BurstListBean.DataBean.ListBean>()
    private lateinit var headview:View
    private var i=1
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        Contents.PUBLICK_URL= TMServerConfig.BASE_URL
        rooView = inflater.inflate(R.layout.home_fgm,null)
        if (ContextCompat.checkSelfPermission(context!!, Manifest.permission.READ_PHONE_STATE)!= PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(context!!, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(context!!, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(context!!, Manifest.permission.RECORD_AUDIO)!= PackageManager.PERMISSION_GRANTED
                )run{
            ActivityCompat.requestPermissions(activity!!, arrayOf(Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE
                    , Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO),0)
        }
        if (null!=TMSharedPUtil.getTMThemeColor(context)&&TMSharedPUtil.getTMThemeColor(context).length>0){
            rooView.loTittle.setBackgroundColor(Color.parseColor(TMSharedPUtil.getTMThemeColor(context)))
        }
        loadDialog= LoadingDialog(context!!)
        initView()
        rooView.btExit.setOnClickListener {
            activity!!.finish()
        }

        return rooView
    }

    override fun onDestroy() {
        LocationUtils.getInstance(context!!).removeLocationUpdatesListener()
        super.onDestroy()

    }
    private fun initData() {
        Log.e("fhpp","碎片里面的token${TMSharedPUtil.getTMToken(context)}")
        OkGo.get<String>(Contents.PUBLICK_URL+ Contents.LIST)
                .params("page",page)
                .params("token",TMSharedPUtil.getTMToken(context))
                .headers("token",TMSharedPUtil.getTMToken(context))
                .execute(object : StringCallback(){
                    override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                        super.onStart(request)
                        loadDialog.show()
                    }
                    override fun onSuccess(response: Response<String>?) {

                        loadDialog.dismiss()
                        spView.onFinishFreshAndLoad()
                        val body = response?.body()
                        val bean = Gson().fromJson(body, BurstListBean::class.java)
                        if (bean?.code==1){
                            if (page==1){
                                datas.clear()
                            }
                            datas.addAll(bean?.data.list)
                            synchronized(this){
                                if (pagerDatas.size==0){
                                    val bannerView = headview.findViewById<BannerView<BurstListBean.DataBean.BannerBean>>(R.id.banner)
                                    pagerDatas.addAll(bean?.data.banner)
                                    bannerView.setViewFactory { item, position, container ->
                                        val bannerBean = item as BurstListBean.DataBean.BannerBean
                                        val imageView = ImageView(container.context)
                                        imageView.scaleType=ImageView.ScaleType.FIT_XY
                                        if (bannerBean.banner_img.contains("http")){
                                            Glide.with(container.context).load(bannerBean.banner_img).apply(GlideUtil.loadImageOption())
                                                    .into(imageView)
                                        }else{
                                            Glide.with(container.context ).load(Contents.PUBLICK_URL+bannerBean.banner_img).apply(GlideUtil.loadImageOption())
                                                    .into(imageView)
                                        }
                                        imageView
                                    }
                                    bannerView.setDataList(pagerDatas)
                                    bannerView.start()
                                }
                            }


                            adp.notifyDataSetChanged()
                        }
                        else if (bean?.code==500){
                            TMSharedPUtil.saveTMToken(context,"")
                            OkGo.get<String>(Contents.PUBLICK_URL+ Contents.LIST)
                                    .params("page",page)
                                    .execute(object : StringCallback(){
                                        override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                                            super.onStart(request)
                                            loadDialog.show()
                                        }
                                        override fun onSuccess(response: Response<String>?) {
                                            loadDialog.dismiss()
                                            spView.onFinishFreshAndLoad()
                                            val body = response?.body()
                                            val bean = Gson().fromJson(body, BurstListBean::class.java)
                                            if (bean?.code==1){
                                                if (page==1){
                                                    datas.clear()
                                                }
                                                datas.addAll(bean?.data.list)
                                                adp.notifyDataSetChanged()


                                                synchronized(this){
                                                    val bannerView = headview.findViewById<BannerView<BurstListBean.DataBean.BannerBean>>(R.id.banner)
                                                    pagerDatas.addAll(bean?.data.banner)
                                                    bannerView.setViewFactory { item, position, container ->
                                                        val bannerBean = item as BurstListBean.DataBean.BannerBean
                                                        val imageView = ImageView(container.context)
                                                        imageView.scaleType=ImageView.ScaleType.FIT_XY
                                                        if (bannerBean.banner_img.contains("http")){
                                                            Glide.with(container.context).load(bannerBean.banner_img).apply(GlideUtil.loadImageOption())
                                                                    .into(imageView)
                                                        }else{
                                                            Glide.with(container.context).load(Contents.PUBLICK_URL+bannerBean.banner_img).apply(GlideUtil.loadImageOption())
                                                                    .into(imageView)
                                                        }
                                                        imageView
                                                    }
                                                    bannerView.setDataList(pagerDatas)
                                                    bannerView.start()
                                                }

                                            }else{
                                                Toast.makeText(context,bean?.msg,Toast.LENGTH_SHORT).show()
                                            }
                                        }
                                    })
                        }
                    }
                })

    }

    private fun initView() {
        initSp()
        /*头布局*/
        headview = LayoutInflater.from(context).inflate(R.layout.burst_head_pager, null)
        headview.btGoBurst.text="我要\n爆料"
        if (!TextUtils.isEmpty(TMSharedPUtil.getTMThemeColor(context))){
            val drawable = headview.btGoBurst.background as GradientDrawable
            drawable.setColor(Color.parseColor(TMSharedPUtil.getTMThemeColor(context)))
        }
        headview.btGoBurst.setOnClickListener {
            val intent = Intent(context, MyBurstAty::class.java)
            startActivity(intent)
        }
        adp=object :BaseQuickAdapter<BurstListBean.DataBean.ListBean,BaseViewHolder>(R.layout.burst_item,datas){
            override fun convert(helper: BaseViewHolder?, item: BurstListBean.DataBean.ListBean?) {
                LogUtil.e("info",Contents.PUBLICK_URL+item?.head_pic?.replace("\\","/"))
                if (item!!.head_pic.contains("http")){
                    Glide.with(mContext).load(item?.head_pic?.replace("\\","/"))
                            .apply(GlideUtil.loadHeadOption())
                            .into(helper?.getView(R.id.userIcon)!!)
                }else{
                    Glide.with(mContext).load(Contents.PUBLICK_URL+"/"+item?.head_pic?.replace("\\","/"))
                            .apply(GlideUtil.loadHeadOption())
                            .into(helper?.getView(R.id.userIcon)!!)
                }


                if (null==item?.member_nickname||item?.member_nickname!!.isEmpty()){
                    helper?.setText(R.id.userName,item?.member_name)
                }else{
                    helper?.setText(R.id.userName,item?.member_nickname)
                }
                helper?.setText(R.id.btZan,item?.laud_num.toString())
                if (null==item.address||item?.address.equals("")||item?.equals("0")){
                    helper?.setText(R.id.tvHowLong, TimeUtils.convertTimeToFormat(item?.create_at?.toLong()!!))
                }else{
                    helper?.setText(R.id.tvHowLong, TimeUtils.convertTimeToFormat(item?.create_at?.toLong()!!)+"发布于"+item?.address)
                }

                val btCheckAllContent = helper?.getView<TextView>(R.id.btCheckAllContent)
                if (item?.content?.length!!>70){
                    helper?.setText(R.id.tvContent,item?.content.substring(0,70))
                    btCheckAllContent?.visibility=View.VISIBLE
                    btCheckAllContent?.setOnClickListener {
                        helper?.setText(R.id.tvContent,item?.content)
                    }
                }else{
                    helper?.setText(R.id.tvContent,item?.content)
                    btCheckAllContent?.visibility=View.GONE
                }
                val btCheckAll = helper?.getView<TextView>(R.id.btCheckAll)
                val thumbLo = helper?.getView<RelativeLayout>(R.id.thumbLo)
                val imgThumb = helper?.getView<ImageView>(R.id.imgThumb)
                val btComment = helper?.getView<ImageView>(R.id.btComment)
                val btZan = helper?.getView<TextView>(R.id.btZan)
                val btShare = helper?.getView<ImageView>(R.id.btShare)
                /*分享*/
                btShare!!.setOnClickListener {
                    val share = TMLinkShare()
                    share.description="${item?.content}"
                    share.title="爆料"
                    if (item?.source_type==1){
                        if (item?.source.size>0){
                            share.thumb=Contents.PUBLICK_URL+item?.source[0]
                        }
                    }else{
                        share.thumb=Contents.PUBLICK_URL+item?.video_thumb
                    }
                    share.url="${Contents.PUBLICK_URL}/application/hlhjburst/asset/index.htm?id=${item?.id}"
                    TMShareUtil.getInstance(mContext).shareLink(share)
                }
                /*点赞*/
                if (item?.is_laud==1){
                    val drawable = resources.getDrawable(R.drawable.ic_bl_dianzan1)
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//对图片进行压缩
                    btZan?.setCompoundDrawables(drawable, null, null, null);
                }else{
                    val drawable = resources.getDrawable(R.drawable.ic_bl_dianzan)
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//对图片进行压缩
                    btZan?.setCompoundDrawables(drawable, null, null, null);
                }
                btZan?.setOnClickListener {
                    OkGo.get<String>(Contents.PUBLICK_URL+Contents.DIANZAN)
                            .params("token", TMSharedPUtil.getTMToken(mContext))
                            .params("burst_id",item?.id)
                            .execute(object :StringCallback(){
                                override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                                    super.onStart(request)
                                    loadDialog.show()
                                }
                                override fun onSuccess(response: Response<String>?) {
                                    loadDialog.dismiss()
                                    val body = response?.body()
                                    val baseBean = Gson().fromJson(body!!, BaseBean::class.java)
                                    if (baseBean.code==1){
                                        if (item?.is_laud==1){
                                            btZan.text = (btZan.text.toString().toInt()-1).toString()
                                            item?.is_laud=0
                                            val drawable = resources.getDrawable(R.drawable.ic_bl_dianzan)
                                            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//对图片进行压缩
                                            btZan?.setCompoundDrawables(drawable, null, null, null);
                                        }else{
                                            btZan.text = (btZan.text.toString().toInt()+1).toString()
                                            item?.is_laud=1
                                            val drawable = resources.getDrawable(R.drawable.ic_bl_dianzan1)
                                            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//对图片进行压缩
                                            btZan?.setCompoundDrawables(drawable, null, null, null);
                                        }
                                    }else if (baseBean.code==500){
                                        GoLoginDialog(context!!).show()
                                    }
                                }
                            })
                }
                /*评论*/
                btComment?.setOnClickListener {
                    EditPop(mContext,item?.id.toString(),"0",object : EditPop.CommentSuccessListener{
                        override fun commmentSuccess(str:String,id:String) {
                            val bean = BurstListBean.DataBean.ListBean.CommentBean()
                            bean.id=id.toInt()
                            bean.one_member_name=TMSharedPUtil.getTMUser(mContext).member_name
                            bean.one_member_nickname=TMSharedPUtil.getTMUser(mContext).member_real_name
                            bean.one_content=str
                            bean.content=str
                            datas[helper?.adapterPosition-1].comment.add(bean)
                            notifyDataSetChanged()

                        }
                    }).showAtLocation(father, Gravity.CENTER and  Gravity.BOTTOM,0,0)
                }
                /*资源加载*/
                val nineRcy = helper?.getView<RecyclerView>(R.id.nineRcy)

                if (item?.source_type==1){
                    thumbLo?.visibility=View.GONE
                    if (item?.source.size>0){
                        nineRcy?.visibility=View.VISIBLE
                        val nineAdp=NineGridAdp(item?.source as ArrayList<String>)
                        val manager = GridLayoutManager(mContext, 3)
                        manager?.isAutoMeasureEnabled=true
                        nineRcy.layoutManager= manager
                        nineRcy.adapter=nineAdp

                        nineAdp?.setOnItemClickListener { adapter, view, position ->
                            val intent = Intent(mContext, PreviewAtyBurst::class.java)
                            intent.putExtra("imgs", item?.source as ArrayList<String>)
                            startActivity(intent)
                        }
                    }else{
                        nineRcy?.visibility=View.GONE
                    }
                }else if (item?.source_type==2){
                    thumbLo?.visibility=View.VISIBLE
                    nineRcy?.visibility=View.GONE
                    thumbLo?.setOnClickListener {
                        val intent = Intent(context!!, VideoPlayAty::class.java)
                        intent.putExtra("url",item?.source[0])
                        intent.putExtra("img",Contents.PUBLICK_URL+item?.video_thumb)
                        startActivity(intent)
                    }

                    GlideUtil.loadImg(mContext,item?.video_thumb,imgThumb)

                }else{
                    nineRcy?.visibility=View.GONE
                    thumbLo?.visibility=View.GONE
                }
                /*加载评论*/
                val myListView = helper?.getView<MyListView>(R.id.commentListView)
                if (null!=item?.comment){
                    if (item?.comment.size>0){
                        if (item?.comment.size>3){
                            btCheckAll?.visibility=View.VISIBLE
                            val tempDatas=ArrayList<BurstListBean.DataBean.ListBean.CommentBean>()
                            tempDatas.add(0,item?.comment[0])
                            tempDatas.add(0,item?.comment[1])
                            tempDatas.add(0,item?.comment[2])
                            val adp = CommentAdp(mContext,tempDatas)
                            myListView?.adapter=adp
                            myListView?.setOnItemClickListener { parent, view, position, id ->
                                EditPop(mContext,item?.id.toString(),tempDatas[position].id.toString(),object : EditPop.CommentSuccessListener{
                                    override fun commmentSuccess(str:String,id:String) {
                                        val bean = BurstListBean.DataBean.ListBean.CommentBean()
                                        bean.id=id.toInt()
                                        bean.member_nickname=TMSharedPUtil.getTMUser(mContext).member_real_name
                                        bean.member_name=TMSharedPUtil.getTMUser(mContext).member_name
                                        if (null==tempDatas[position].member_name||tempDatas[position].member_name.isEmpty()){
                                            bean.one_member_name=tempDatas[position].one_member_name
                                            bean.one_member_nickname=tempDatas[position].one_member_nickname

                                        }else{
                                            bean.one_member_name=tempDatas[position].member_name
                                            bean.one_member_nickname=tempDatas[position].member_nickname
                                        }
                                        bean.content=str
                                        bean.one_content=str
//                                        Toast.makeText(mContext,"耳机评论为空了?${str}",Toast.LENGTH_SHORT).show()
                                        datas[helper?.adapterPosition-1].comment.add(bean)
                                        notifyDataSetChanged()
                                    }
                                }).showAtLocation(father, Gravity.CENTER and  Gravity.BOTTOM,0,0)
                            }
                            btCheckAll?.setOnClickListener {
                                val intent = Intent(mContext, BurstDetailAty::class.java)
                                intent.putExtra("type","1")
                                intent.putExtra("bean",item)
                                intent.putExtra("id",item.id)
                                intent.putExtra("nickName",item.member_nickname)
                                intent.putExtra("memberName",item.member_name)
                                intent.putExtra("time",TimeUtils.convertTimeToFormat(item.create_at.toLong()))
                                intent.putExtra("content",item.content)
                                intent.putExtra("icon",item.head_pic)
                                startActivity(intent)

                            }
                        }else{
                            btCheckAll?.visibility=View.GONE
                            val adp = CommentAdp(mContext,item?.comment as ArrayList<BurstListBean.DataBean.ListBean.CommentBean>)
//                            val myListView = helper?.getView<MyListView>(R.id.commentListView)
                            myListView?.adapter=adp
                            myListView?.setOnItemClickListener { parent, view, position, id ->
                                EditPop(mContext,item?.id.toString(),item.comment[position].id.toString(),object : EditPop.CommentSuccessListener{
                                    override fun commmentSuccess(str:String,id:String) {
                                        val bean = BurstListBean.DataBean.ListBean.CommentBean()
                                        bean.id=id.toInt()
                                        bean.member_nickname=TMSharedPUtil.getTMUser(mContext).member_real_name
                                        bean.member_name=TMSharedPUtil.getTMUser(mContext).member_name
                                        if (null==item?.comment[position].member_name||item?.comment[position].member_name.isEmpty()){
                                            bean.one_member_name=item?.comment[position].one_member_name
                                            bean.one_member_nickname=item?.comment[position].one_member_nickname
                                        }else{
                                            bean.one_member_name=item?.comment[position].member_name
                                            bean.one_member_nickname=item?.comment[position].member_nickname
                                        }
                                        bean.content=str
                                        bean.one_content=str
                                        LogUtil.e("到底是写什么数据${bean.member_nickname}-${bean.member_name}" +
                                                "-${bean.one_member_name}-${bean.one_member_nickname}")
                                        datas[helper?.adapterPosition-1].comment.add(bean)
                                        notifyDataSetChanged()
                                    }
                                }).showAtLocation(father, Gravity.CENTER and  Gravity.BOTTOM,0,0)
                            }
                        }
                    }else{
                        btCheckAll?.visibility=View.GONE
                        val tempDatas=ArrayList<BurstListBean.DataBean.ListBean.CommentBean>()
                        val adp = CommentAdp(mContext,tempDatas)
                        myListView.adapter=adp
                    }
                }else{
                    val tempDatas=ArrayList<BurstListBean.DataBean.ListBean.CommentBean>()
                    val adp = CommentAdp(mContext,tempDatas)
                    myListView.adapter=adp

                }


            }
        }
        rooView.recyclerview.adapter=adp
        rooView.recyclerview.layoutManager= LinearLayoutManager(context!!, LinearLayout.VERTICAL,false)
        adp.addHeaderView(headview)

    }
    private fun initSp() {
        rooView.spView.header= DefaultHeader(context!!)
        rooView.spView.footer= DefaultFooter(context!!)
        rooView.spView.setListener(this)
    }
    override fun onLoadmore() {
        page++
        initData()
    }

    override fun onRefresh() {
        page=1
        datas.clear()
        initData()
    }


    /*onresum*/
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser&&isResumed){
            onResume()
        }else if (!isVisibleToUser){
            onPause()
        }
    }

    override fun onResume() {
        super.onResume()
        if (userVisibleHint){
            if (BurstFgm.isFromImage){
                BurstFgm.isFromImage=false
            }else{
                page=1
                datas.clear()
                initData()
            }

        }
    }
}